package com.minidb.engine;

import java.util.*;

public class PlanNode {
    //json格式输出
    public String op;  // 算子类型：SeqScan, Filter, Project, Insert, CreateTable, Delete
    public Map<String,Object> props = new HashMap<>();
    public List<PlanNode> children = new ArrayList<>();

    public PlanNode(String op) { this.op = op; }

    public void addChild(PlanNode c) { children.add(c); }

    public String toJSON() {
        StringBuilder sb = new StringBuilder();
        toJSON(sb,0);
        return sb.toString();
    }

    private void toJSON(StringBuilder sb, int indent) {
        String pad = "  ".repeat(indent);
        sb.append(pad).append("{\n");
        sb.append(pad).append("  \"op\": \"").append(op).append("\",\n");
        if (!props.isEmpty()) {
            sb.append(pad).append("  \"props\": {");
            int i=0;
            for (var e : props.entrySet()) {
                sb.append("\"").append(e.getKey()).append("\": \"").append(e.getValue()).append("\"");
                if (++i < props.size()) sb.append(", ");
            }
            sb.append("},\n");
        }
        if (!children.isEmpty()) {
            sb.append(pad).append("  \"children\": [\n");
            for (int i=0;i<children.size();i++) {
                children.get(i).toJSON(sb, indent+2);
                if (i<children.size()-1) sb.append(",");
                sb.append("\n");
            }
            sb.append(pad).append("  ]\n");
        }
        sb.append(pad).append("}");
    }
}
